using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Models;
using System.IO;

namespace DocumentCreationSystem
{
    /// <summary>
    /// 项目修复工具类
    /// </summary>
    public class ProjectFixUtility
    {
        private readonly ILogger<ProjectFixUtility> _logger;
        private readonly IProjectService _projectService;
        private readonly IDataStorageService _dataStorage;

        public ProjectFixUtility(IServiceProvider serviceProvider)
        {
            _logger = serviceProvider.GetRequiredService<ILogger<ProjectFixUtility>>();
            _projectService = serviceProvider.GetRequiredService<IProjectService>();
            _dataStorage = serviceProvider.GetRequiredService<IDataStorageService>();
        }

        /// <summary>
        /// 修复项目ID为6的小说项目不存在问题
        /// </summary>
        public async Task<bool> FixMissingNovelProjectAsync(int projectId, string novelTitle = "默认小说标题", string creativeDirection = "默认创作方向")
        {
            try
            {
                _logger.LogInformation($"开始修复项目ID {projectId} 的小说项目问题...");

                // 1. 检查基础项目是否存在
                var project = await _projectService.GetProjectAsync(projectId);
                if (project == null)
                {
                    _logger.LogError($"项目ID {projectId} 不存在，无法修复");
                    return false;
                }

                // 2. 检查小说项目是否已存在
                var existingNovelProject = await _projectService.GetNovelProjectAsync(projectId);
                if (existingNovelProject != null)
                {
                    _logger.LogInformation($"小说项目已存在，ID: {existingNovelProject.Id}");
                    return true;
                }

                // 3. 创建缺失的小说项目记录
                _logger.LogInformation("创建缺失的小说项目记录...");
                
                var novelProject = new NovelProject
                {
                    ProjectId = projectId,
                    Title = novelTitle,
                    CreativeDirection = creativeDirection,
                    TargetChapterCount = 1000,
                    TargetWordsPerChapter = 6500,
                    Status = "Planning",
                    CreatedAt = DateTime.Now,
                    UpdatedAt = DateTime.Now
                };

                var createdNovelProject = await _dataStorage.CreateNovelProjectAsync(novelProject);
                
                _logger.LogInformation($"小说项目修复成功，新ID: {createdNovelProject.Id}");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"修复项目ID {projectId} 的小说项目时发生错误");
                return false;
            }
        }

        /// <summary>
        /// 为临时项目创建正式的项目记录
        /// </summary>
        public async Task<Project?> CreateFormalProjectFromTempAsync(string projectName, string projectPath, string novelTitle, string creativeDirection)
        {
            try
            {
                _logger.LogInformation($"为临时项目创建正式记录: {projectName}");

                // 1. 创建正式的基础项目
                var project = await _projectService.CreateProjectAsync(
                    projectName,
                    "Novel",
                    projectPath,
                    $"小说项目: {novelTitle}");

                _logger.LogInformation($"基础项目创建成功，ID: {project.Id}");

                // 2. 创建小说项目记录
                var novelProject = await _projectService.CreateNovelProjectAsync(
                    projectName,
                    novelTitle,
                    creativeDirection,
                    projectPath);

                _logger.LogInformation($"小说项目创建成功，ID: {novelProject.Id}");

                return project;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"为临时项目创建正式记录时发生错误: {projectName}");
                return null;
            }
        }

        /// <summary>
        /// 诊断项目状态
        /// </summary>
        public async Task DiagnoseProjectStatusAsync(int projectId)
        {
            try
            {
                _logger.LogInformation($"=== 诊断项目ID {projectId} 的状态 ===");

                // 检查基础项目
                var project = await _projectService.GetProjectAsync(projectId);
                if (project == null)
                {
                    _logger.LogWarning($"基础项目不存在: ID {projectId}");
                }
                else
                {
                    _logger.LogInformation($"基础项目存在: 名称={project.Name}, 类型={project.Type}, 路径={project.RootPath}");
                }

                // 检查小说项目
                var novelProject = await _projectService.GetNovelProjectAsync(projectId);
                if (novelProject == null)
                {
                    _logger.LogWarning($"小说项目不存在: 项目ID {projectId}");
                }
                else
                {
                    _logger.LogInformation($"小说项目存在: ID={novelProject.Id}, 标题={novelProject.Title}, 状态={novelProject.Status}");
                }

                // 显示所有项目
                var allProjects = await _projectService.GetAllProjectsAsync();
                _logger.LogInformation($"数据库中总项目数: {allProjects.Count}");
                
                foreach (var p in allProjects)
                {
                    _logger.LogInformation($"  项目: ID={p.Id}, 名称={p.Name}, 类型={p.Type}");
                }

                _logger.LogInformation("=== 诊断完成 ===");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"诊断项目ID {projectId} 时发生错误");
            }
        }

        /// <summary>
        /// 重置数据存储（谨慎使用）
        /// </summary>
        public async Task<bool> ResetDataStorageAsync()
        {
            try
            {
                _logger.LogWarning("警告：即将重置数据存储，所有数据将丢失！");
                
                // 这里可以添加重置逻辑，但需要谨慎
                // 暂时只记录警告
                _logger.LogWarning("数据存储重置功能暂未实现，请手动删除Data文件夹");
                
                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重置数据存储时发生错误");
                return false;
            }
        }
    }
}
